<template>
    <div class="flex-content">
        <!-- <image style="border-radius: 5%;margin-top: 5%;width: 100%;height: 300rpx;"
            src="https://cxj.szzkba.cn/upload/i/2024/06/05/172949.jpeg">
        </image> -->
        <nut-form ref="formRef" :model-value="formData">
            <img class="status" src="https://cxj.szzkba.cn/upload/i/2024/08/27/155630.png"
                v-if="formData.user_Status == '0'" alt="">
            <nut-form-item label="头像" prop="image_Url" required :rules="[{ required: true, message: '请上传头像' }]">
                <nut-uploader :url="uploadUrl" v-model:file-list="headFileList" accept="image/*" @success="picSucc"
                    maximum="1" multiple>
                </nut-uploader>
            </nut-form-item>
            <nut-form-item label="姓名" prop="user_Nickname" required :rules="[{ required: true, message: '请填写姓名' }]">
                <nut-input v-model="formData.user_Nickname" placeholder="请输入姓名" type="text"
                    @blur="customBlurValidate('user_Nickname')" />
            </nut-form-item>
            <nut-form-item label="性别" prop="user_Sex" required :rules="[{ required: true, message: '请选择性别' }]">
                <!-- <nut-radio-group v-model="formData.user_Sex" direction="horizontal"
                    @change="customBlurValidate('user_Sex')">
                    <nut-radio label="1">男</nut-radio>
                    <nut-radio label="2">女</nut-radio>
                </nut-radio-group> -->
                <div @click="sexShow = true" style="text-align: right;justify-content: flex-end;" class="flex-a">
                    <div>{{ formData.user_Sex.length > 0 ? String(formData.user_Sex)
                        : '请选择性别' }}</div>
                    <Right size="12" color="#CECECE" />
                </div>
                <nut-popup v-model:visible="sexShow" position="bottom">
                    <nut-picker v-model="formData.user_Sex" :columns="sexColumns" title="请选择性别" @confirm="sexConfirm"
                        @cancel="sexShow = false" />
                </nut-popup>
            </nut-form-item>
            <nut-form-item label="年龄" prop="user_Age" required :rules="[{ required: true, message: '请填写年龄' }]">
                <nut-input v-model="formData.user_Age" placeholder="请输入年龄" type="text"
                    @blur="customBlurValidate('user_Age')" />
            </nut-form-item>
            <nut-form-item label="简介" prop="user_Enterts" star-position="left" required
                :rules="[{ required: true, message: '请填写简介' }]">
                <nut-textarea v-model="formData.user_Enterts" text-align="right" :max-length="100" autosize
                    placeholder="请输入简介" @blur="customBlurValidate('user_Enterts')" />
            </nut-form-item>
            <!-- <nut-form-item label="身高" prop="user_Tall" required :rules="[{ required: true, message: '请填写身高' }]">
                    <nut-row>
                        <nut-col :span="21">
                            <nut-input v-model="formData.user_Tall" placeholder="请输入身高" type="text"
                                @blur="customBlurValidate('user_Tall')" />
                        </nut-col>
                        <nut-col :span="3">cm</nut-col>
                    </nut-row>
                </nut-form-item>
                <nut-form-item label="体重" prop="user_Weight" required :rules="[{ required: true, message: '请填写体重' }]">
                    <nut-row>
                        <nut-col :span="21">
                            <nut-input v-model="formData.user_Weight" placeholder="请输入体重" type="text"
                                @blur="customBlurValidate('user_Weight')" />
                        </nut-col>
                        <nut-col :span="3">kg</nut-col>
                    </nut-row>
                </nut-form-item> -->
            <nut-form-item label="入驻城市">
                <div @click="show = true" style="text-align: right;justify-content: flex-end;" class="flex-a">
                    <div>{{ formData.city.length > 0 ? String(formData.city)
                        : '请选择城市' }}</div>
                    <Right size="12" color="#CECECE" />
                </div>
                <nut-popup v-model:visible="show" position="bottom">
                    <nut-picker v-model="formData.city" :columns="columns" title="请选择城市" @confirm="confirm"
                        @cancel="show = false" />
                </nut-popup>
            </nut-form-item>
            <div class="flex-content2">
                <div class="card-title">身份证正反面</div>
                <div class="tip">*单张图片不能超过5M</div>
                <div style="margin:0 5%">
                    <nut-uploader :url="uploadUrl" accept="image/*" @success="IdCardSucc"
                        v-model:file-list="defaultFileList" maximum="2" multiple>
                    </nut-uploader>
                </div>
            </div>
            <div class="flex-content2">
                <div class="flex-a flex-b select-pro">
                    <text class="title">服务项目</text>
                    <div @click="addClass">
                        <text>请选择服务项目</text>
                        <Right size="12" color="#CECECE" />
                    </div>
                </div>
                <!-- <nut-button style="margin: 2% 5%;font-size:20rpx" shape="square" plain size="mini" color="#21C38F"
                    @click="addClass">
                    <template #icon>
                        <Uploader size="10" />
                    </template>添加</nut-button> -->
                <nut-popup v-model:visible="classShow" position="bottom">
                    <nut-picker v-model="sort" :columns="classList" title="请选择分类" @confirm="confirmClass"
                        @cancel="classShow = false" />
                </nut-popup>
                <block v-for="(item, index) in serviceList">
                    <div style="display: flex; margin: 5% 0;align-items: center;">
                        <text class="pro-list">{{ item.text
                            }}</text>
                        <CircleClose size="14" color="red" @click="delClass(item, index)" />
                    </div>
                    <div class="btn-list">
                        <nut-checkbox-group v-model="formData.PageSettingId">
                            <nut-checkbox :label="ele.ID" shape="button" v-for="ele in item.list"> {{ ele.project_Name
                                }}
                            </nut-checkbox>
                        </nut-checkbox-group>
                    </div>
                </block>
            </div>
            <div style="border-bottom: 1px solid #e6e6e6;"></div>
            <div class="flex-content">
                <!-- <div style="margin: 5% 0;">
                    <text style="color:#999999;font-size: 16px;">*请如实填写个人信息</text>
                </div> -->
                <nut-form-item prop="agreeVal" required :rules="[{ required: true, message: '请同意用户协议' }]">
                    <div style="margin-bottom:20rpx;white-space: nowrap;">
                        <nut-checkbox v-model="formData.agreeVal" @change="customBlurValidate('agreeVal')">
                            <span>提交即同意</span><span style="color:#F2B862">《用户协议(服务承包方)》</span>
                        </nut-checkbox>
                    </div>
                </nut-form-item>
                <div>
                    <nut-button color="#F0A93F" :loading="isLoading" @click="submit" block
                        style="margin:0 auto 20rpx;width: 94%;border-radius: 10rpx;">{{
                            !formData.ID ? '提交' : '重新提交' }}</nut-button>
                </div>
            </div>
        </nut-form>
    </div>
</template>

<script lang="ts">
import { reactive, toRefs, onMounted } from 'vue';
import { BASE_URL, imgUrl } from './../../../../utils/index'
import Taro from '@tarojs/taro';
import { Left, Uploader, CircleClose, Right } from '@nutui/icons-vue-taro';
import { createUser, getIndexClass, getIndexService, getUserDetailsList, getFindUserDetails, updateUserDetails } from '../../../../api/index'
export default {
    components: {
        Left,
        Uploader,
        CircleClose,
        Right
    },
    setup() {
        const confirm = ({ selectedValue, selectedOptions }) => {
            console.log(selectedValue[0], selectedOptions[0])
            state.show = false
            console.log(state.formData.city)
        };
        const sexConfirm = ({ selectedValue, selectedOptions }) => {
            console.log(selectedValue[0], selectedOptions[0])
            state.sexShow = false
            console.log(state.formData.user_Sex)
        };
        const confirmClass = ({ selectedValue, selectedOptions }) => {
            console.log(selectedValue[0], selectedOptions[0])
            state.classShow = false
            let data = selectedOptions[0]
            let n = state.serviceList.findIndex(item => { return item.value == selectedOptions[0].value })
            if (n == -1) {
                state.serviceList.push({
                    text: data.text,
                    value: data.value,
                    list: [] as any
                })
                getList(data.value, { pageType: data.value })
            }
        };
        const getList = (value, data) => {
            getIndexService(data).then(res => {
                if (res.code == 0) {
                    let list = state.serviceList
                    let i = list.findIndex((item) => { return item.value == value })
                    let arr = res.data.list
                    arr.forEach(item => {
                        item.ID = item.ID + ''
                    })
                    state.serviceList[i].list.push(...arr)
                }
            })
        }
        const submit = () => {
            console.log(state.formRef)
            state.formRef?.validate().then(({ valid, errors }) => {
                if (valid) {
                    if (state.formData.PageSettingId.length) {
                        console.log('success:', state.formData)
                        state.isLoading = true
                        state.formData.user_ID = state.user.uuid
                        state.formData.user_City = state.formData.city[0]
                        if (state.formData.ID) {
                            let list = state.formData.PageSettingId
                            let arr = list.map(item => item.toString())
                            state.formData.PageSettingId = arr
                            updateUserDetails(state.formData).then(res => {
                                if (res.code == 0) {
                                    Taro.showToast({
                                        title: '提交成功',
                                        icon: 'success',
                                        duration: 2000
                                    })
                                    state.isLoading = false
                                    setTimeout(() => {
                                        jumpTo('/packageA/pages/mypage/index')
                                    }, 500)
                                }
                            })
                        } else {
                            createUser(state.formData).then(res => {
                                if (res.code == 0) {
                                    Taro.showToast({
                                        title: '提交成功',
                                        icon: 'success',
                                        duration: 2000
                                    })
                                    state.isLoading = false
                                    setTimeout(() => {
                                        jumpTo('/packageA/pages/mypage/index')
                                    }, 500)
                                }
                            })
                        }
                    } else {
                        Taro.showToast({
                            title: '请至少选择一个服务项目',
                            icon: 'error'
                        })
                    }
                } else {
                    console.warn('error:', errors)
                }
            })
        };
        // 失去焦点校验
        const customBlurValidate = (prop) => {
            state.formRef?.validate(prop).then(({ valid, errors }) => {
                if (valid) {
                    console.log('success:', state.formData)
                } else {
                    console.warn('error:', errors)
                }
            })
        };
        const state = reactive({
            isLoading: false,
            list: [
                {
                    proj_name: '乐平市废弃矿山生态修复综合治理项目',
                    proj_no: '赣建乐招字[2023] 第 21 号',
                    proj_location: '九江市',
                    proj_type: '房屋及市政工程',
                }
            ],
            formData: {
                image_Url: '',
                PageSettingId: [] as any,
                user_ID: '',
                user_Nickname: '',
                user_Sex: [],
                user_Age: '',
                user_Tall: '0',
                user_Weight: '0',
                user_City: '' as any,
                city: [],
                user_Enterts: '',
                user_Services: '',
                user_Leisures: '',
                user_Balls: '',
                enterts: [],
                services: [],
                leisures: [],
                balls: [],
                agreeVal: false,
            },
            formRef: null,
            columns: [
                { text: '上饶', value: '上饶' },
            ],
            sexColumns: [
                { text: '男', value: '男' },
                { text: '女', value: '女' },
            ],
            sexShow: false,
            show: false,
            val: '',
            uploadUrl: BASE_URL + '/fileUploadAndDownload/uploadPublic',
            defaultFileList: [],
            headFileList: [],
            user: {},
            classList: [],
            sort: '',
            classShow: false,
            serviceList: [],
            settleInfor: [],
        });
        onMounted(() => {
            Taro.setNavigationBarTitle({
                title: '立即入驻'
            })
            Taro.getStorage({
                key: 'user',
                success: function (res) {
                    state.user = res.data ? res.data : {}
                    console.log(state.user.uuid)
                    getDetail(state.user.uuid)
                }
            })
            getIndexClass({ ID: 12 }).then(res => {
                if (res.code == 0) {
                    let list = res.data.resysDictionary.sysDictionaryDetails, arr = [] as any
                    list.forEach(item => {
                        arr.push({ text: item.label, value: item.value })
                    })
                    state.classList = arr
                }
            })
            getSettleInDetails()
        })
        const picSucc = (data, option, fileItem) => {
            console.log(JSON.parse(data.data.data).data.file.url)
            state.formData.image_Url = BASE_URL + '/' + JSON.parse(data.data.data).data.file.url
        }
        const IdCardSucc = (data, option, fileItem) => {
            console.log(JSON.parse(data.data.data).data.file.url)
            if (state.formData.user_Services == '') {
                state.formData.user_Services = BASE_URL + '/' + JSON.parse(data.data.data).data.file.url
            } else {
                state.formData.user_Leisures = BASE_URL + '/' + JSON.parse(data.data.data).data.file.url
            }
        }
        const jumpTo = (path) => {
            Taro.navigateTo({ url: path })
        }
        const addClass = () => {
            state.classShow = true
        }
        const delClass = (item, index) => {
            state.serviceList.splice(index, 1)
        }
        const getSettleInDetails = () => {
            getUserDetailsList().then(res => {
                if (res.code == 0) {
                    for (var i in res.data.list) {
                        res.data.list[i].user_Enterts = res.data.list[i].user_Enterts.split(",")
                        res.data.list[i].user_Services = res.data.list[i].user_Services.split(",")
                        res.data.list[i].user_Leisures = res.data.list[i].user_Leisures.split(",")
                        res.data.list[i].user_Balls = res.data.list[i].user_Balls.split(",")
                    }
                    let list = res.data.list, arr = []
                    list.forEach(item => {
                        if (item.user_ID == state.user.uuid) {
                            state.settleInfor.push(item)
                        }
                    })
                    console.log(state.settleInfor)
                    if (state.settleInfor.length > 0) {
                        state.formData.user_Nickname = state.settleInfor[0].user_Nickname
                        state.formData.image_Url = state.settleInfor[0].image_Url
                        state.formData.user_Sex = state.settleInfor[0].user_Sex
                        state.formData.user_Age = state.settleInfor[0].user_Age
                        state.formData.city = state.settleInfor[0].user_City
                        state.formData.user_Tall = state.settleInfor[0].user_Tall
                        state.formData.user_Weight = state.settleInfor[0].user_Weight
                        state.formData.user_Enterts = state.settleInfor[0].user_Enterts
                        state.formData.user_Services = state.settleInfor[0].user_Services
                        state.formData.user_Leisures = state.settleInfor[0].user_Leisures
                        state.formData.user_Balls = state.settleInfor[0].user_Balls
                    }
                }
            })
        }
        const getDetail = (id) => {
            getFindUserDetails({ User_ID: id }).then(res => {
                if (res.code == 0) {
                    state.formData = res.data.reuserDetails
                    state.formData.PageSettingId = res.data.reuserDetails.pageSettingList
                    state.formData.image_Url = res.data.reuserDetails.imageUrl
                    state.formData.city = res.data.reuserDetails.user_City.split(' ')
                    state.defaultFileList = [
                        {
                            name: '',
                            url: res.data.reuserDetails.user_Services,
                            status: 'success',
                            message: '上传成功',
                            type: 'image'
                        },
                        {
                            name: '',
                            url: res.data.reuserDetails.user_Leisures,
                            status: 'success',
                            message: '上传成功',
                            type: 'image'
                        }
                    ]
                    state.headFileList = [
                        {
                            name: '',
                            url: res.data.reuserDetails.imageUrl,
                            status: 'success',
                            message: '上传成功',
                            type: 'image'
                        },
                    ]
                    let list = res.data.reuserDetails.pageSettings, arr = [] as any
                    list.forEach((item, index) => {
                        arr.push({
                            text: item.label,
                            value: item.value,
                            list: []
                        })
                        item.pageSettings.forEach((ele, ind) => {
                            arr[index].list.push(ele)
                        })
                    })
                    state.serviceList = arr
                }
            })
        }
        return {
            confirm,
            submit,
            customBlurValidate,
            picSucc,
            IdCardSucc,
            jumpTo,
            addClass,
            delClass,
            getDetail,
            confirmClass,
            getList,
            getSettleInDetails,
            sexConfirm,
            ...toRefs(state)
        };

    }
}
</script>

<style lang="scss">
.flex-content {
    position: relative;
    padding-top: 20rpx;

    .nut-cell-group__wrap {
        margin: 0 !important;
    }

    .nut-uploader {
        justify-content: flex-end;
    }

    .input-text {
        text-align: right !important;
        color: #0F1234;
        font-size: 26rpx;
    }

    .nut-form-item__label {
        color: #0F1234;
        font-size: 26rpx;
        font-weight: bold;
    }

    .nut-radio-group {
        display: flex !important;
        justify-content: flex-end;
        align-items: center;
    }

    .nut-radio {
        margin-bottom: 0 !important;
    }

    .status {
        position: absolute;
        right: 20rpx;
        top: 50rpx;
        width: 122rpx;
        height: 96rpx;
        z-index: 9999;
    }

    .nut-textarea {
        height: 150rpx;
    }

    .nut-icon-check-checked {
        color: #21C38F !important;
    }


    .nut-icon-checked {
        color: #21C38F !important;
    }
}

.flex-content2 {
    margin: 0 4%;

    .card-title {
        color: #171A3B;
        font-size: 26rpx;
        font-weight: bold;
        margin: 20rpx 0 10rpx;
    }

    .tip {
        color: #A9A9A9;
        font-size: 24rpx;
        margin-bottom: 24rpx;
    }

    .pro-list {
        color: #171A3B;
        font-size: 26rpx;
        font-weight: bold;
        margin-right: 10rpx;
    }

    .nut-checkbox__button--active {
        border-color: #F9DFB9 !important;
        background: #FDF6EC !important;
    }

    .nut-checkbox__button {
        color: #2D304D !important;
        border-radius: 10rpx !important;
        background: #F5F5F5;
        height: 80rpx !important;
        white-space: normal !important;
        padding: 0 10rpx !important;
        text-align: center !important;
        width: 100% !important;
        box-sizing: border-box !important;
        display: flex !important;
        justify-content: center !important;
    }

    .nut-checkbox--button {
        width: 32% !important;
        box-sizing: border-box !important;
        margin-bottom: 20rpx !important;
        text-align: center !important;
    }

    .nut-checkbox--button:nth-child(3n+2) {
        margin: 0 2%;
    }

    .select-pro {
        display: flex;
        align-items: center;
        padding: 20rpx 0;
        border-top: 1rpx solid #F8F9FC;
        border-bottom: 1rpx solid #F8F9FC;
        margin-top: 20rpx;

        div {
            font-size: 26rpx;
            color: #D2D2D2;
        }
    }

    .title {
        font-size: 26rpx;
        color: #43455F;
        font-weight: bold;
    }

    .nut-uploader {
        justify-content: flex-start !important;
    }
}

.nut-checkbox__button {
    white-space: nowrap;
}

.nut-checkbox.nut-checkbox--button {
    margin: 0;
}

.nut-checkbox__label {
    display: flex;
}
</style>